簡單說cookie,session
cookie的好處,給使用者更好的使用者體驗,減少伺服器負擔(存在於client端的瀏覽器)
缺點是有安全問題,且無法存入大量資料
ex:一些廣告會再第一次跳進去的時候彈出,關閉時cookie就會記錄
session大概和cookie相反,安全度較高,可以儲存大量資料(資料庫),session會和cookie搭配使用
ex:用戶名稱
我又再創了一個app,setting,model那些我就不再一一做了
先貼程式碼,再來講
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from three.models import Person
import time
# Create your views here.
def login(request):
if request.session.get('username'):
return redirect(reverse('three:mine'))
return render(request, 'three/login.html')
def do_login(request):
username = request.POST.get('username')
password = request.POST.get('password')
person = Person.objects.filter(name=username).filter(password=password)
person = person.first()
if person:
response = HttpResponse('set cookie')
response.set_cookie('token', person.token)
request.session['username'] = username
return redirect(reverse('three:mine'))
return redirect(reverse('three:login'))
def mine(request):
username = request.session.get('username')
if username is None:
return redirect(reverse('three:login'))
token = request.COOKIES.get('token')
person = Person.objects.get(token=token)
return render(request, 'three/mine.html', context={'username': username})
def logout(request):
response = redirect(reverse('three:login'))
request.session.flush()
return response
def register(request):
return render(request, 'three/register.html')
@csrf_exempt
def do_register(request):
person = Person()
username = request.POST.get('username')
password = request.POST.get('password')
person.name = username
person.password = password
person.token = generate_token(username)
person.save()
return redirect(reverse('three:login'))
def generate_token(name):
return name + str(time.ctime())
urls.py
from django.contrib import admin
from django.urls import path, re_path
from three import views
urlpatterns = [
path('login/', views.login, name='login'),
path('do_login/', views.do_login, name='dologin'),
path('mine/', views.mine, name='mine'),
path('logout/', views.logout, name='logout'),
path('register/', views.register, name='register'),
path('do_register/', views.do_register, name='doregister'),
]
login.html
<form action="{% url 'three:dologin'%}" method="post">
{% csrf_token %}
<span>username: <input type="text" name="username"></span>
<br>
<span>password: <input type='password' name="password"></span>
<br>
<button>submit</button>
</form>
<a href="{% url 'three:register'%}">register</a>
沒貼的部分應該也很好打出來,可以試者打
判斷是否已經登入,已經登入就跳到mine.html
login
利用post的方式取得使用者輸入的資料,根據輸入判斷是否正確,正確就設置seesion,不正確返回login
do_login
判斷session是否存在,是就顯示mine.html的畫面,不是就回到login
mine
清空session,重新導向到login
logout
register應該沒什麼好講的
@csrf_exempt 讓你再post請求時不會因為csrf而擋住,也可以寫在html就像login.html一樣(exempt:豁免)
do_register
token 這邊就不細說,session很cookie就很好用了,token通常用在手機